// pages/me/me.js
const app = getApp()
import Toast from '../../component/toast/toast';
import IMController from '../../controller/im.js'
let cerealsToast;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        userInfo: {},
        logoImg: '../../assets/image/default_logo.png',
        bindPhone: '未绑定手机号',
        cerealsNum:-1
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        cerealsToast = this.selectComponent('#cereals-toast')
        if (app.globalData.isLogin) {
            
            // console.log(JSON.stringify(this.data.userInfo));
        } else if (!this.data.canIUse) {
            wx.getUserInfo({
                success: res => {
                    // app.globalData.userInfo = res.userInfo
                    res.userInfo.iv = res.iv;
                    res.userInfo.encryptedData = res.encryptedData;
                    this.userLogin(res.userInfo, function (info) {
                        that.imLogin(info.Token ,info.Id);
                        app.saveCredit(function (count) {
                            cerealsToast.show(count);
                        });
                        this.setData({
                            userInfo: info,
                            hasUserInfo: true,
                            bindPhone: info.MobileNumber ? "手机号已绑定" : "未绑定手机号"
                        })

                    });
                }
            })
        }
    },
    imLogin: function (token, account) {
        new IMController({
            token: token,
            account: account
        })
    },
    userLogin(userInfo, _success) {
        wx.showLoading({
            title: '正在登录...',
            mask: true
        });
        let that = this;
        let data = {
            Code: app.globalData.code,
            NickName: userInfo.nickName,
            Gender: userInfo.gender,
            ProfilePicture: userInfo.avatarUrl,
            EncryptedData: userInfo.encryptedData,
            Iv: userInfo.iv
        };
        console.log("url："+app.globalData.serverAddress.login+"，"+JSON.stringify(data));
        // return;
        wx.login({
            success: res => {
                app.globalData.code = res.code;
                wx.request({
                    url: app.globalData.serverAddress.login,
                    data: {
                        Code: app.globalData.code,
                        NickName: userInfo.nickName,
                        Gender: userInfo.gender,
                        ProfilePicture: userInfo.avatarUrl,
                        EncryptedData: userInfo.encryptedData,
                        Iv: userInfo.iv
                    },
                    header: {
                        'Authorization': "Bearer " + app.globalData.token
                    },
                    method: 'POST',
                    success: function (res) {
                        console.log(res);
                        if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                            app.globalData.isLogin = true;
                            app.userInfo = res.data.BodyContent;
                            if (app.userInfo.MobileNumber) {
                                app.globalData.isBindPhone = true;
                            }
                            if (_success) {
                                // console.log(_success);
                                _success(res.data.BodyContent);
                            }
                            app.checkLoactionAuth();
                            that.getUserInfoCredit();
                        }
                        Toast(res.data.Message);
                    },
                    fail: function (res) { console.log("login fail：" + res); },
                    complete: function (res) { wx.hideLoading(); },
                })
            }
        });
        
    },
    loginClick() {

    },
    clickMyEvaluate(){
      if(!this.checkStatus()){
        return;
      }
      wx.navigateTo({
        url: '/pages/new-pages/my-evaluate/my-evaluate'
      })
    },
    //我的作品
    myProduct(){
        if (!this.checkStatus()) {
            return;
        }
        wx.navigateTo({
            url: '/pages/new-pages/my-product/my-product'
        })
    },
    recruitClick(){
        this.getEnterpriseInfoById(function (verifyStatus) {
            if (verifyStatus == 0) {
                Toast("您还未通过企业认证呦");
            }
            if (verifyStatus == 1) {
                Toast("企业认证审核中...");
            }
            if (verifyStatus == 2) {
                wx.navigateTo({
                    url: '/pages/compony-pages/compony-recruit/compony-recruit'
                })
            }
            if (verifyStatus == 3) {
                wx.navigateTo({
                    url: '/pages/compony-pages/auth-fail/auth-fail'
                })
            }
        });
    },
    issueJobClick(){
        // wx.navigateTo({
        //     url: '/pages/compony-pages/issue-job/issue-job'
        // })
        this.getEnterpriseInfoById(function (verifyStatus) {
            if (verifyStatus == 0) {
                Toast("发布职位需要先通过企业认证呦");
            }
            if (verifyStatus == 1) {
                Toast("企业认证审核中...");
            }
            if (verifyStatus == 2) {
                wx.navigateTo({
                    url: '/pages/compony-pages/issue-job/issue-job'
                })
            }
            if (verifyStatus == 3) {
                wx.navigateTo({
                    url: '/pages/compony-pages/auth-fail/auth-fail'
                })
            }
        });
    },
    componyMainClick(){
        this.getEnterpriseInfoById(function (verifyStatus) {
            if (verifyStatus == 0) {
                Toast("请先通过企业认证！");
            }
            if (verifyStatus == 1) {
                Toast("企业认证审核中...");
            }
            if (verifyStatus == 2) {
                wx.navigateTo({
                    url: '/pages/compony-pages/compony-main/compony-main'
                })
            }
            if (verifyStatus == 3) {
                wx.navigateTo({
                    url: '/pages/compony-pages/auth-fail/auth-fail'
                })
            }
        });
    },
    //远程工作技能评估
    evaluateClick(){
        if (!this.checkStatus()) {
            return;
        }
        this.getUserTestScore();
    },
    
    componyClick(){
        if (!this.checkStatus()) {
            return;
        }
        this.getEnterpriseInfoById(function (verifyStatus){
            if (verifyStatus == 0) {
                wx.navigateTo({
                    url: '/pages/compony-pages/compony-auth/compony-auth'
                })
            }
            if (verifyStatus == 1) {
                Toast("正在审核...");
            }
            if (verifyStatus == 2) {
                Toast("已认证，请勿重复认证！");
            }
            if(verifyStatus == 3){
                wx.navigateTo({
                    url: '/pages/compony-pages/auth-fail/auth-fail'
                })
            }
        });
    },
    myCollect(){
        if (!this.checkStatus()) {
            return;
        }
        wx.navigateTo({
            url: '/pages/mes/follow/follow'
        })
    },
    bindGetUserInfo(e) {
        if (this.data.hasUserInfo) {
            return;
        }
        if (!this.data.canIUse) {
            wx.getUserInfo({
                success: res => {
                    // app.globalData.userInfo = res.userInfo
                    res.userInfo.iv = res.iv;
                    res.userInfo.encryptedData = res.encryptedData;
                    this.userLogin(res.userInfo, function (info) {
                        that.imLogin(info.Token, info.Id);
                        app.saveCredit(function (count) {
                            cerealsToast.show(count);
                        });
                        this.setData({
                            userInfo: info,
                            hasUserInfo: true,
                            bindPhone: info.MobileNumber ? "手机号已绑定" : "未绑定手机号"
                        })
                    });
                }
            });
            return;
        }
        let that = this;
        wx.getSetting({
            success: res => {
                console.log(JSON.stringify(res))
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            console.log("已授权：" + JSON.stringify(res.userInfo));
                            // 可以将 res 发送给后台解码出 unionId
                            res.userInfo.iv = res.iv;
                            res.userInfo.encryptedData = res.encryptedData;
                            console.log(res.userInfo);
                            // app.globalData.userInfo = res.userInfo;
                            that.userLogin(res.userInfo , function(info){
                                // console.log(info.Id , info.Token);
                                that.imLogin(info.Token, info.Id);
                                app.saveCredit(function (count) {
                                    cerealsToast.show(count);
                                });
                                that.setData({
                                    userInfo: info,
                                    hasUserInfo: true,
                                    bindPhone: info.MobileNumber ? "手机号已绑定" : "未绑定手机号"
                                })
                            });
                        }
                    })
                } else {
                    Toast("授权失败，请重新登录！");
                }
            }
        });
    },
    // 闲将工作APP
    workClick(){
        app.globalData.globalWebUrl = app.globalData.agreementUrl.xjWork;
        wx.navigateTo({
            url: '/pages/agreement-web/agreement-web?title=闲将工作APP'
        })
    },
    exitLogin() {
        let that = this;
        wx.showModal({
            title: '退出登录',
            content: '您是否要退出登录！',
            showCancel: true,
            cancelColor: '#4EB262',
            confirmColor:'#333',
            success: function(res) {
                if (res.confirm) {
                    app.globalData.isLogin = false;
                    app.globalData.isBindPhone = false;
                    app.userInfo = null;
                    that.setData({
                        userInfo: null,
                        hasUserInfo: false,
                        bindPhone: "未绑定手机号",
                        cerealsNum:-1
                    });
                    app.globalData.nim.destroy({
                        done: function () {
                            console.log('destroy nim done !!!')
                            app.globalData.nim = null
                            wx.clearStorage()
                        }
                    })
                }
            }
        })
    },
    bindPhoneClick(){
        if (!this.data.hasUserInfo) {
            Toast("请先登录");
            return;
        }
        wx.navigateTo({
            url: '/pages/mes/bind-phone/bind-phone'
        })
    },
    getPhoneNumber(e) {
        let that = this;
        if (!this.data.hasUserInfo){
            Toast("请先登录");
            return;
        }
        if (app.globalData.isBindPhone){
            Toast("手机号已绑定");
            return;
        }
        console.log("UserInfoId:" + app.userInfo.Id + ",EncryptedData：" + e.detail.encryptedData + ",Iv：" + e.detail.iv);
        // return;
        if (e.detail.errMsg == 'getPhoneNumber:ok') {
            let data = {
                UserInfoId: app.userInfo.Id,
                EncryptedData: e.detail.encryptedData,
                Iv: e.detail.iv
            };
            wx.request({
                url: app.globalData.serverAddress.bindPhone,
                method: 'POST',
                data: data,
                header: {
                    'Authorization': "Bearer " + app.globalData.token
                },
                success: function(res) {
                    console.log(JSON.stringify(res));
                    if (res.statusCode == 200) {
                        if (res.data.CodeStatus == 20000) {
                            app.globalData.isBindPhone = true;
                            that.setData({
                                bindPhone: '手机号已绑定'
                            });
                        }
                    } else {
                        console.log("getPhoneNumber:" + JSON.stringify(res));
                    }
                    Toast(res.data.Message);
                },
                fail: function(res) {
                    console.log("getPhoneNumber:" + JSON.stringify(res));
                }
            })
        } else {
            Toast("请重新绑定！")
        }
    },
    checkStatus(){
        if (!this.data.hasUserInfo) {
            Toast("请先登录");
            return false;
        }else if (!app.globalData.isBindPhone) {
            Toast("请绑定手机号码");
            return false;
        }
        return true;
    },
    toIssueClick() {
        if(!this.checkStatus()){
            return;
        }
        // if (app.userInfo.IsVerified == 0 || app.userInfo.IsVerified == 1) {
        //     Toast("您还未实名认证，请先实名认证！");
        //     return;
        // }
        let avatarUrl = this.data.userInfo.ProfilePicture;
        let nickName = this.data.userInfo.NickName;
        wx.navigateTo({
            url: '/pages/mes/service/service?avatarUrl=' + avatarUrl + "&nickName=" + nickName,
        })
    },
    myPurse() {
        if (!this.checkStatus()) {
            return;
        }
        wx.navigateTo({
            url: '/pages/new-pages/my-purse/my-purse',
        });
    },
    openLive(){
        if (!this.checkStatus()) {
            return;
        }
        wx.navigateTo({
            url: '/pages/mes/open-live/open-live',
        });
    },
    myIssues() {
        if (!this.checkStatus()) {
            return;
        }
        wx.navigateTo({
            url: '/pages/mes/issue/issue',
        });
    },
    myClientServer() {
        if (!this.checkStatus()) {
            return;
        }
        wx.navigateTo({
            url: '/pages/new-pages/my-employer-order/my-employer-order',
        })
    },
    myAdoptClick() {
        if (!this.checkStatus()) {
            return;
        }
        wx.navigateTo({
            url: '/pages/new-pages/my-employee/my-employee',
        });
    },
    authClick() {
        if (!this.checkStatus()) {
            return;
        }
        if (app.userInfo.IsVerified == 0){
            wx.navigateTo({
                url: '/pages/mes/authentication/authentication',
            });
            return;
        }
        this.getUserInfoVerified();
    },
    //更多协同产品
    productClick(){
        app.globalData.globalWebUrl = app.globalData.agreementUrl.xjUrl;
        wx.navigateTo({
            url: '/pages/agreement-web/agreement-web?title=闲将'
        })
    },
    getUserInfoVerified() {
        wx.showLoading({
            title: '加载中...',
            mask:true
        });
        wx.request({
            url: app.globalData.serverAddress.getUserInfoVerified,
            data: {
                userId: app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    // console.log("success:" + JSON.stringify(res.data.BodyContent));
                    if (res.data.BodyContent.VerifyStatus){
                        app.userInfo.IsVerified = res.data.BodyContent.VerifyStatus;
                    }
                    if (res.data.BodyContent.VerifyStatus == 0) {
                        wx.navigateTo({
                            url: '/pages/mes/authentication/authentication',
                        });
                    }else{
                        wx.navigateTo({
                            url: '/pages/mes/auth-result/auth-result?parmas=' + JSON.stringify(res.data.BodyContent),
                        })
                    }
                } else {
                    console.log("statusCode!=200：" + JSON.stringify(res.data));
                    Toast(res.data.Message);
                }
            },
            fail: function(res) {
                console.log("fail：" + JSON.stringify(res.data));
                Toast(res.data.Message);
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    getEnterpriseInfoById(func) {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        wx.request({
            url: app.globalData.serverAddress.getEnterpriseInfoById,
            data: {
                userInfoId: app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function (res) {
                console.log('getEnterpriseInfoById success', res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000){
                        let verifyStatus = res.data.BodyContent.VerifyStatus;
                        if (verifyStatus == 2) {
                            app.globalData.enterpriseInfo = res.data.BodyContent;
                        }
                        if (func) {
                            func(verifyStatus);
                        }
                    }else{
                        func(0);
                    }  
                }else{
                    // Toast("请求")
                }
            },
            fail: function (res) { console.log("getEnterpriseInfoById fail", res) },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    getUserInfoCredit(){
        let that = this;
        wx.request({
            url: app.globalData.serverAddress.getUserInfoCredit,
            data: {
                userInfoId: app.userInfo.Id
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function (res) {
                // console.log('getUserInfoCredit success', res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        that.setData({
                            cerealsNum: res.data.BodyContent.CreditCount
                        })
                    }
                } else {
                    // Toast("请求")
                }
            },
            fail: function (res) { console.log("getEnterpriseInfoById fail", res) },
            complete: function (res) { wx.hideLoading(); },
        })
    },
    //我的粮草
    toCereals(){
        if (!this.checkStatus()) {
            return;
        }
        wx.navigateTo({
            url: '/pages/new-pages/my-cereals/my-cereals?cerealsNum=' + this.data.cerealsNum
        })
    },
    toHome() {
        if (!this.checkStatus()) {
            return;
        }
        wx.navigateTo({
            url: '/pages/new-pages/main-page/main-page'
        });
    },
    getUserTestScore(){
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        wx.request({
            url: app.globalData.serverAddress.getUserTestScore,
            data: {
                userInfoId:app.userInfo.Id,
                testType:1
            },
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log("getUserTestScore:",res.data)
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    if(res.data.BodyContent.Score >= 12){
                        Toast('您已通过评估')
                    }else{
                        wx.navigateTo({
                            url: '/pages/new-pages/select-evaluate/select-evaluate'
                        })
                    }
                }
                //无成绩
                else if (res.data.CodeStatus == 40005){
                  wx.navigateTo({
                    url: '/pages/new-pages/select-evaluate/select-evaluate'
                  })
                }
            },
            fail: function(res) {
                console.error('getUserTestScore' , res)
                if (res.data.Message){
                    Toast(res.data.Message);
                }
            },
            complete: function(res) {wx.hideLoading()},
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.setData({
          userInfo: app.userInfo,
          hasUserInfo: app.userInfo ? true : false,
          bindPhone: app.globalData.isBindPhone ? "手机号已绑定" : "未绑定手机号",
          cerealsNum:-1
        })
        if(app.userInfo){
            this.getUserInfoCredit();
        }
        // this.setData({
        //     bindPhone: app.globalData.isBindPhone ?"手机号已绑定":"未绑定手机号"
        // });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})